﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace mesoBoard.Data.Repositories
{
    public class RankRepository : IRankRepository
    {
        private mbEntities db;

        public RankRepository(mbEntities mbDataContext)
        {
            this.db = mbDataContext;
        }

        public IEnumerable<Rank> GetRanks()
        {
            return db.Ranks.AsEnumerable();
        }

        public Rank GetRank(int RankID = 0, int PostCount = 0)
        {
            if (RankID != 0)
                return db.Ranks.FirstOrDefault(x => x.RankID == RankID);

            if (PostCount != 0)
                return db.Ranks.Where(x => x.PostCount - PostCount < 0).OrderByDescending(x => x.PostCount).FirstOrDefault();

            return null;
        }

        public bool RankExists(int RankID, int PostCount)
        {
            return db.Ranks.Any(x => x.RankID != RankID && x.PostCount == PostCount);
        }

        public void UpdateRank(Rank TheRank)
        {
            if (TheRank.EntityKey == null)
                TheRank.EntityKey = ((Rank)db.GetObjectByKey(new System.Data.EntityKey("mbEntities.Ranks", "RankID", TheRank.RankID))).EntityKey;

            db.Ranks.ApplyCurrentValues(TheRank);
            db.SaveChanges();
        }

        public void CreateRank(Rank TheRank)
        {
            db.Ranks.AddObject(TheRank);
            db.SaveChanges();
        }

        public void DeleteRank(int RankID)
        {
            db.Ranks.DeleteObject(GetRank(RankID: RankID));
            db.SaveChanges();
        }

        public void SubmitChanges()
        {
            db.SaveChanges();
        }
    }

}
